package com.sky.controller.admin;

import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/admin/employee")
@Api(tags = "员工相关接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /*
     新增员工
     @RequestBody : 作用把json数据转成javabean对象
     */
    @PostMapping
    @ApiOperation("新增员工")
    public Result save(@RequestBody EmployeeDTO employeeDTO){
        log.info("新增员工：{}",employeeDTO);
        employeeService.save(employeeDTO);
        return Result.success();
    }



    @PutMapping("/editPassword")
    @ApiOperation(value = "修改密码")
    public Result updatePassword(@RequestBody PasswordEditDTO passwordEditDTO){
        log.info("修改密码：{}",passwordEditDTO);
        employeeService.updatePassword(passwordEditDTO);
        return Result.success();
    }

    /**
     * 退出成功
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "员工登出")
    public Result<String> logout(){
        return Result.success();
    }



//    http://localhost:8080/admin/employee/home
    @GetMapping("/home")
    public Result<String> home(){
        System.out.println("home");
        return Result.success("这是首页");
    }

    // @RequestBody : 前端传递过来的json数据转成对象
    @PostMapping("/login")
    @ApiOperation(value = "员工登录")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO){
        // 1 ：调用service，查询数据库
        Employee employee =  employeeService.login(employeeLoginDTO);
        // 2 ：如果登录成功，需要使用JWT令牌，返回给客户端
        Map<String, Object> map = new HashMap<>();
        // 存放员工id
        map.put("empId",employee.getId());
        // 创建JWT令牌
        // 参数一：令牌的密钥，随便写一个字符串
        // 参数二：令牌的过期时间，单位是毫秒值
        // 参数三：设置的信息
        String token = JwtUtil.createJWT("sxx", 3600000, map);
        // 返回数据给客户端
        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .name(employee.getName())
                .token(token)
                .userName(employee.getUsername())
                .build();
        return Result.success(employeeLoginVO);

    }


}
